//
//  PentahoIPPUCAppDelegate.m
//  PentahoIPPUC
//
//  Created by Bill Seyler on 6/10/10.
//  Copyright Pentaho Corporation 2010. All rights reserved.
//

#import "PentahoIPPUCAppDelegate.h"
#import "RootViewController.h"
#import "SolutionNode.h"
#import "SolutionParser.h"
#import "PreferencesViewController.h"

@implementation PentahoIPPUCAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize setupButton;
@synthesize serverUrl;
@synthesize userid;
@synthesize password;

@synthesize rootNode;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	[window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
	[self loadPrefs];
	[self connect];
	return YES;
}

- (BOOL)connect {
	NSString *connectionStr = [NSString stringWithFormat:@"%@%@&userid=%@&password=%@", serverUrl, kRepoRequest, userid, password];
	NSLog(@"Connection String: %@", connectionStr);
	NSURL *url = [[NSURL alloc] initWithString:connectionStr];
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
	
	SolutionParser *solutionParser = [[SolutionParser alloc] init];
	[xmlParser setDelegate:solutionParser];
	
	BOOL success = [xmlParser parse];
	
	if (success) {
		NSLog(@"No Errors");
		[self setRootNode:[solutionParser rootNode]];
	} else {
		NSLog(@"Error, Error, Error!!!");
	}
	[solutionParser release];
	[xmlParser release];
	return success;
}

- (void)loadPrefs {
	NSString *filePath = [self dataFilePath];
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
		[self setServerUrl:[array objectAtIndex:0]];
		[self setUserid:[array objectAtIndex:1]];
		[self setPassword:[array objectAtIndex:2]];
	} else {
		[self setServerUrl:kServerURI];
		[self setUserid:kUserName];
		[self setPassword:kPassword];		
	}
}

- (void)applicationWillTerminate:(UIApplication *)application {
	NSMutableArray *array = [[NSMutableArray alloc] init];
	[array addObject:[self serverUrl]];
	[array addObject:[self userid]];
	[array addObject:[self password]];
	[array writeToFile:[self dataFilePath] atomically:YES];
	[array release];
}

- (NSString *)dataFilePath {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	return [documentsDirectory stringByAppendingPathComponent:kFileName];
}
#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	[navigationController release];
	[window release];
	[super dealloc];
}

- (IBAction)doSetup:(id)sender
{
	NSLog(@"in doSetup");
	PreferencesViewController *prefController = [[PreferencesViewController alloc] init];
	[window addSubview:[prefController view]];
}


@end

